package com.wtwd.campus.utils;



import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.TreeMap;

/**
 * @Author ldaoliang
 * @Date create in 14:04 2021/5/14
 * @Description
 */
public class RequestParseUtils {

    /**
     * 从HttpServletRequest对象中取得请求体中的json
     * @param request
     * @return
     */
    public static JSONObject requestParse(HttpServletRequest request) {
        // 使用LinkedHashMap保证key的顺序，
        JSONObject json = new JSONObject();
        InputStreamReader inputReader;
        try {
            inputReader = new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8);
            BufferedReader bufferReader = new BufferedReader(inputReader);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = bufferReader.readLine()) != null) {
                sb.append(line);
            }
            TreeMap<String,Object> map = JSONObject.parseObject(sb.toString(),TreeMap.class);
            // parseObject时，Feature.OrderedField按照jsonString的顺序转jsonObject。因此需要把流读出来的放到Map中进行排序
            json = JSONObject.parseObject(JSONObject.toJSONString(map), Feature.OrderedField);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }
}
